/*
 * @Author: 
 * @Date: 2024-05-15 20:39:05
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2025-01-23 14:09:44
 * @Description: 用户服务
 */
import { Provide, Inject } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entity/user.entity';
import { TokenService } from './token.service'; // 引入 TokenService
import * as bcrypt from 'bcrypt';

@Provide()
export class UserService {
  @InjectEntityModel(User)
  UserModel: Repository<User>;

  @Inject()
  tokenService: TokenService;

  /**
   * 注册用户
   */
  async register(username: string, email: string, password: string,roleId: string,subsystemId: string) {
    try {
      if (!username || !email || !password) {
        return { success: false, message: '用户名、邮箱和密码均不能为空' };
      }

      const existingUser = await this.UserModel.findOne({ where: [{ username }, { email }] });
      if (existingUser) {
        return { success: false, message: '用户名或邮箱已存在' };
      }

      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(password, salt);
      const newUser = this.UserModel.create({
        username, 
        email,
        password: hashedPassword,
        salt,
        roleId,
        subsystemId
      });

      const savedUser = await this.UserModel.save(newUser);
      return { success: true, data: savedUser, message: '注册成功' };
    } catch (error) {
      console.error('注册用户失败:', error);
      return { success: false, message: '注册失败，请稍后再试' };
    }
  }

  /**
   * 用户登录
   */
  async login(username: string, password: string) {
    try {
      if (!username || !password) {
        return { success: false, message: '用户名和密码均不能为空' };
      }

      const user = await this.UserModel.findOne({ where: { username } });
      if (!user) {
        return { success: false, message: '用户名或密码错误' };
      }

      const isPasswordValid = await bcrypt.compare(password, user.password);
      if (!isPasswordValid) {
        return { success: false, message: '用户名或密码错误' };
      }

      const tokens = await this.tokenService.generateTokens(user.id);
      return {
        success: true,
        message: '登录成功',
        data: {
          user: {
            id: user.id,
            username: user.username,
            email: user.email,
            roleId: user.roleId,
            subsystemId:user.subsystemId 
          },
          ...tokens,
        },
      };
    } catch (error) {
      console.error('用户登录失败:', error);
      return { success: false, message: '登录失败，请稍后再试' };
    }
  }

  /**
   * 注销用户
   */
  async logout(userId: number) {
    try {
      const result = await this.tokenService.revokeTokens(userId);
      if (!result) {
        return { success: false, message: '注销失败' };
      }
      return { success: true, message: '注销成功' };
    } catch (error) {
      console.error('注销失败:', error);
      return { success: false, message: '注销失败，请稍后再试' };
    }
  }

  /**
   * 分页获取用户列表，支持按用户名模糊查询
   * @param page 当前页码
   * @param limit 每页数量
   * @param search 模糊查询关键词
   */
  async getAllUsers(page: number, limit: number, search?: string, orderBy: 'ASC' | 'DESC' = 'DESC') {
    const skip = (page - 1) * limit;
  
    const query = this.UserModel.createQueryBuilder('user');
  
    if (search) {
      query.where('user.username LIKE :search', { search: `%${search}%` });
    }
  
    // 按动态的排序方式排序
    query.orderBy('user.createDate', orderBy);
  
    const [data, total] = await query.skip(skip).take(limit).getManyAndCount();
  
    return {
      total,
      data,
      message: '查询成功',
    };
  }
  

  /**
   * 根据 ID 获取用户
   */
  async getUserById(id: number) {
    try {
      const user = await this.UserModel.findOne({ where: { id } });
      if (!user) {
        return { success: false, message: '用户未找到' };
      }
      return { success: true, data: user, message: '获取用户详情成功' };
    } catch (error) {
      console.error('获取用户详情失败:', error);
      return { success: false, message: '获取用户详情失败，请稍后再试' };
    }
  }

  /**
   * 更新用户信息
   */
  async updateUser(id: number, updateData: Partial<User>) {
    try {
      const user = await this.UserModel.findOne({ where: { id } });
      if (!user) {
        return { success: false, message: '用户未找到' };
      }

      // 字段过滤
      const allowedFields = ['email', 'password', 'isActive', 'roleId', 'subsystemId'];
      Object.keys(updateData).forEach((key) => {
        if (!allowedFields.includes(key)) {
          delete updateData[key];
        }
      });

      if (updateData.password) {
        const salt = await bcrypt.genSalt(10);
        updateData.password = await bcrypt.hash(updateData.password, salt);
      }

      Object.assign(user, updateData);
      const updatedUser = await this.UserModel.save(user);

      return { success: true, data: updatedUser, message: '用户信息更新成功' };
    } catch (error) {
      console.error('更新用户信息失败:', error);
      return { success: false, message: '更新用户信息失败，请稍后再试' };
    }
  }

  /**
   * 删除用户
   */
  async deleteUser(id: number) {
    try {
      const user = await this.UserModel.findOne({ where: { id } });
      if (!user) {
        return { success: false, message: '用户未找到' };
      }

      await this.tokenService.revokeTokens(user.id);
      await this.UserModel.remove(user);

      return { success: true, message: '用户删除成功' };
    } catch (error) {
      console.error('删除用户失败:', error);
      return { success: false, message: '删除用户失败，请稍后再试' };
    }
  }
}
